package com.example.geoaimavlink_android.utils;

import android.text.TextUtils;
import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Ronny
 * @date 2019/5/10.
 * description：
 */
public class LinuxCommandUtil {

    private static ExecutorService mServices;

    public static ArrayList<String> runCommandRetLine(String command) {
        ArrayList<String> ret = new ArrayList<>();
        Process process = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            is = new DataInputStream(process.getInputStream());
            os.writeBytes(command + "\n");
          /*  os.writeBytes("setprop service.adb.tcp.port 5555" + "\n");
            os.writeBytes("stop adbd" + "\n");
            os.writeBytes("start adbd" + "\n");*/
            os.writeBytes("exit\n");
            os.flush();
            String line = null;
            while ((line = is.readLine()) != null) {
                if (!TextUtils.isEmpty(line)) {
                    ret.add(line);
                }
            }
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return ret;
    }

    public static String runCommand(String command) {
        Process process = null;
        String result = "";
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            is = new DataInputStream(process.getInputStream());
            os.writeBytes(command + "\n");
          /*  os.writeBytes("setprop service.adb.tcp.port 5555" + "\n");
            os.writeBytes("stop adbd" + "\n");
            os.writeBytes("start adbd" + "\n");*/
            os.writeBytes("exit\n");
            os.flush();
            String line = null;
            while ((line = is.readLine()) != null) {
                result += line;
            }
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    public static String runCommandNoRoot(String command) {
        Process process = null;
        String result = "";
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec(command);
            os = new DataOutputStream(process.getOutputStream());
            is = new DataInputStream(process.getInputStream());
            String line = null;
            while ((line = is.readLine()) != null) {
                result += line;
            }
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    public static void click(String targetText, CmdCallback callback){

        if(mServices == null){
            mServices = Executors.newCachedThreadPool();
        }
        mServices.execute(new Runnable() {
            @Override
            public void run() {

                HashMap<String,String> itemMap = new HashMap<>();
                FileInputStream inputStream = null;
                try {
                    runCommand("uiautomator dump /sdcard/ui.txt");
                    XmlPullParser parser = Xml.newPullParser();
                    inputStream = new FileInputStream("/sdcard/ui.txt");
                    parser.setInput(inputStream, null);
                    int event = parser.getEventType();

                    int clickCounter = 0;
                    int editCounter = 0;
                    while (event != XmlPullParser.END_DOCUMENT){
                        if(parser.getAttributeCount() > 0){
                            if(!TextUtils.isEmpty(parser.getAttributeValue(null, "text"))) {
                                itemMap.put(parser.getAttributeValue(null, "text"), parser.getAttributeValue(null, "bounds"));
                            }else if("true".equals(parser.getAttributeValue(null, "clickable"))){
                                String targetId = "";
                                if(!TextUtils.isEmpty(parser.getAttributeValue(null, "resource-id"))){
                                    targetId = parser.getAttributeValue(null, "resource-id");
                                }else if(!TextUtils.isEmpty(parser.getAttributeValue(null, "content-desc"))){
                                    targetId = parser.getAttributeValue(null, "content-desc");
                                }else{
                                    targetId = parser.getAttributeValue(null, "class")+clickCounter;
                                    clickCounter++;
                                }

                                itemMap.put(targetId, parser.getAttributeValue(null, "bounds"));
                            }else if("android.widget.EditText".equals(parser.getAttributeValue(null, "class"))){
                                itemMap.put("android.widget.EditText"+editCounter, parser.getAttributeValue(null, "bounds"));
                                editCounter++;
                            }
                        }
                        event = parser.next();
                    }

                    int tapX = -1;
                    int tapY = -1;
                    for(Map.Entry<String,String> item : itemMap.entrySet()){
                        if(item.getKey().toLowerCase().equals(targetText.toLowerCase())){
                            try {
                                int startX = Integer.parseInt(item.getValue().split(",")[0].split("\\[")[1]);
                                int startY = Integer.parseInt(item.getValue().split(",")[1].split("\\]")[0]);
                                int endX = Integer.parseInt(item.getValue().split(",")[1].split("\\[")[1]);
                                int endY = Integer.parseInt(item.getValue().split(",")[2].split("\\]")[0]);
                                tapX = startX + (endX - startX) / 2;
                                tapY = startY + (endY - startY) / 2;
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }

                    }

                    if(tapX > 0 && tapY > 0) {
                        runCommand("input tap " + tapX + " "+ tapY);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(inputStream != null){
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                if(callback != null){
                    callback.onResult(itemMap);
                }
            }
        });

    }

    public interface CmdCallback{
        void onResult(Object result);
    }
}
